/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * 递归每次取最大值，然后再构建左右子树
 * @param {number[]} nums
 * @return {TreeNode}
 */
var constructMaximumBinaryTree = function (nums) {
    return constructLevel(nums)
};
function constructLevel(nums) {
    if (nums.length === 0) return null

    let maxNumIndex = 0

    for (let i = 0; i < nums.length; i++) {
        if (nums[i] > nums[maxNumIndex]) {
            maxNumIndex = i
        }
    }

    const node = new TreeNode(nums[maxNumIndex]);

    node.left = constructLevel(nums.slice(0, maxNumIndex))
    node.right = constructLevel(nums.slice(maxNumIndex + 1))

    return node
}


/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
var constructMaximumBinaryTree = function (nums) {
    return constructLevel(0, nums.length - 1, nums)
};

function constructLevel(left, right, nums) {
    if (left > right) return null

    let maxNumIndex = left

    for (let i = left + 1; i <= right; i++) {
        if (nums[i] > nums[maxNumIndex]) {
            maxNumIndex = i
        }
    }

    let node = new TreeNode(nums[maxNumIndex]);

    node.left = constructLevel(left, maxNumIndex - 1, nums)
    node.right = constructLevel(maxNumIndex + 1, right, nums)

    return node
}